<template>
  <div class="waterfallItem" :data-index="item.dataIndex">
    <div class="cover" v-if="!noImage">
      <img
        v-if="loaded"
        :src="item.src"
        alt="图片"
        :style="{
          width: item.imgWidth + 'px',
          height: item.imgHeight + 'px',
        }"
      />
    </div>
    <div
      class="content"
      v-if="!onlyImage"
      :style="{ width: item.blockWidth + 'px' }"
    >
      <h3>{{ item.title }}</h3>
      <div class="value">{{ item.value }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, ref } from "vue";

const props = withDefaults(
  defineProps<{
    item: any;
    onlyImage?: boolean;
    noImage?: boolean;
  }>(),
  {
    onlyImage: false,
    noImage: false,
  }
);

const loaded = ref(false);
const height = ref("auto");

onBeforeMount(() => {
  if (!props.noImage) {
    height.value = "100%";
    new Promise((resolve) => {
      const image = new Image();
      image.src = props.item.src;
      if (image.complete) {
        loaded.value = true;
        resolve(true);
        return;
      }

      image.onload = () => {
        loaded.value = true;
        resolve(true);
      };

      image.onerror = (error) => {
        console.error(props.item.src, error);
        loaded.value = true;
        resolve(true);
      };
    });
  }
});
</script>

<style scoped lang="less">
.waterfallItem {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .cover {
    display: flex;
    flex: 1;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .content {
    flex-shrink: 0;
    box-sizing: border-box;
    h3 {
      margin: 0;
      padding: 0;
      font-weight: bolder;
      font-size: 14px;
      color: #fff;
    }
    .value {
      color: #fff;
    }
  }
}
.v-enter-active,
.v-leave-active {
  opacity: 1;
  transition: all 0.4s linear;
  will-change: opacity;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  will-change: opacity;
}
</style>
